package com.horsen.service.aliyun.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.horsen.service.aliyun.service.FileService;
import com.horsen.service.aliyun.utils.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * 文件 服务类
 *
 * @author Horsen
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private OSSProperties ossProperties;

    /**
     * 上传文件至阿里云OSS
     *
     * @param inputStream      输入流
     * @param module           文件夹名称
     * @param originalFilename 原始文件名
     * @return 文件url地址
     */
    @Override
    public String upload(InputStream inputStream, String module, String originalFilename) {
        String endpoint = ossProperties.getEndpoint();
        String keyId = ossProperties.getKeyid();
        String keySecret = ossProperties.getKeysecret();
        String bucketName = ossProperties.getBucketname();

        // 判断oss实例是否存在,如果不存在则创建,如果存在则获取
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
        if (!ossClient.doesBucketExist(bucketName)) {
            // 创建bucket
            ossClient.createBucket(bucketName);
            // 设置oss实例的访问权限为公共读
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }
        // 文件名格式: uuid.扩展名
        String fileName = UUID.randomUUID().toString();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String key = module + "/" + fileName + fileExtension;
        // 文件上传至阿里云
        ossClient.putObject(bucketName, key, inputStream);
        // 关闭OSSClient
        ossClient.shutdown();
        // 返回url地址
        return "https://" + bucketName + "." + endpoint + "/" + key;
    }


    /**
     * 从阿里云OSS删除文件
     *
     * @param url 文件的url地址
     */
    @Override
    public void deleteFile(String url) {
        String endpoint = ossProperties.getEndpoint();
        String keyId = ossProperties.getKeyid();
        String keySecret = ossProperties.getKeysecret();
        String bucketName = ossProperties.getBucketname();
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
        // 截取出objectName
        String hostName = "https://" + bucketName + "." + endpoint + "/";
        String objectName = url.substring(hostName.length());
        System.out.println("url = " + url);
        System.out.println("hostName = " + hostName);
        System.out.println("objectName = " + objectName);
        ossClient.deleteObject(bucketName, objectName);
        // 关闭OSSClient
        ossClient.shutdown();
    }
}
